<route lang="json5" type="page">
{
  layout: 'tabbar',
  style: {
    navigationBarTitleText: '分类',
  },
}
</route>

<template>
  <view class="category">
    <htm-popup />
    <wd-popup
      v-model="state.show"
      position="right"
      custom-style="width: 550rpx;"
      @click-modal="handleModal"
      :close-on-click-modal="false"
    >
      <view class="mt-5">
        <text class="ml-5">状态</text>
        <wd-checkbox-group v-model="state.query.status" cell shape="button">
          <wd-checkbox
            :modelValue="status"
            v-for="(status, index) in state.statusList"
            :key="index"
          >
            {{ status }}
          </wd-checkbox>
        </wd-checkbox-group>
        <text class="ml-5">标签</text>
        <wd-checkbox-group v-model="state.query.tags" cell shape="button">
          <wd-checkbox :modelValue="tag" v-for="(tag, index) in state.tagsList" :key="index">
            {{ tag }}
          </wd-checkbox>
        </wd-checkbox-group>
      </view>
      <view class="!flex justify-around absolute bottom-26 w-full">
        <htm-button @click="handleCancel('popup')" plain type="info">清除</htm-button>
        <htm-button custom-class="!ml-2" @click="handleConfirm('popup')">确认</htm-button>
      </view>
    </wd-popup>

    <wd-search
      custom-style="box-sizing: border-box; width: 100vw; height: 100rpx; margin-bottom: -8rpx"
      v-model="state.query.upcCode"
      placeholder-left
      hide-cancel
      @search="handleSearch"
    />
    <view class="wraper">
      <htm-sidebar
        v-model="state.query.categoryId"
        @change="({ value }) => handleChange({ type: 'sidebar', value })"
      >
        <htm-sidebar-item
          v-for="(item, index) in state.categories.filter((x) => x.level === 1)"
          :key="index"
          :value="item.id"
          :label="item.type_desc"
          :child-ids="state.categories.filter((x) => x.p_id === item.id).map((x) => x.id)"
        >
          <htm-sidebar-item
            v-for="(itemChild, indexChild) in state.categories.filter((x) => x.p_id === item.id)"
            :key="indexChild"
            :value="itemChild.id"
            :label="itemChild.type_desc"
          ></htm-sidebar-item>
        </htm-sidebar-item>
      </htm-sidebar>
      <view class="content">
        <scroll-view
          class="category-scroll-view"
          scroll-y
          scroll-with-animation
          :show-scrollbar="false"
          :scroll-top="scrollTop"
          :throttle="false"
          @scrolltolower="handleScrolltolower"
        >
          <wd-cell-group border use-slot>
            <template #title>
              <wd-sticky :offset-top="46">
                <view class="category-sticky">
                  <wd-radio-group
                    v-model="state.query.sortRule"
                    cell
                    shape="button"
                    custom-class="category-radio-group"
                    @change="(value) => handleChange({ type: 'radio-group', value })"
                  >
                    <wd-radio
                      v-for="(item, index) in state.sortRules"
                      :key="index"
                      :value="item.value"
                    >
                      {{ item.label }}
                    </wd-radio>
                    <wd-radio
                      value=""
                      v-if="
                        state.query.sortRule !== 'pricedesc' && state.query.sortRule !== 'priceasc'
                      "
                    >
                      价格
                    </wd-radio>
                    <wd-radio value="priceasc" v-if="state.query.sortRule === 'priceasc'">
                      价格
                      <wd-icon name="arrow-thin-up" size="24rpx"></wd-icon>
                    </wd-radio>
                    <wd-radio value="pricedesc" v-if="state.query.sortRule === 'pricedesc'">
                      价格
                      <wd-icon name="arrow-thin-down" size="24rpx"></wd-icon>
                    </wd-radio>
                  </wd-radio-group>
                  <view class="category-filter">
                    <htm-button
                      custom-style="margin-left: 5rpx;color: black;"
                      type="text"
                      @click="handleFilter"
                    >
                      筛选
                      <wd-icon name="filter" size="20rpx"></wd-icon>
                    </htm-button>
                  </view>
                </view>
              </wd-sticky>
            </template>
            <htm-card
              v-for="item in state.productList"
              :key="item.id"
              direction="horizontal"
              v-bind="item"
            />
            <wd-loadmore
              :state="state.loadmoreState"
              finished-text="没有更多了"
              @reload="handleReload"
            />
          </wd-cell-group>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import htmSidebar from '@/components/htm-sidebar/htm-sidebar.vue'
import htmSidebarItem from '@/components/htm-sidebar-item/htm-sidebar-item.vue'
import htmCard from '@/components/htm-card/htm-card.vue'
import htmPopup from '@/components/htm-popup/htm-popup.vue'
import { ref, nextTick } from 'vue'
import {
  getQueryCondition,
  IBrand,
  ICategory,
  IProductQueryParams,
  IProductQueryResult,
  IQueryConditionResult,
  ISortRule,
  productQuery,
} from '@/service/detail/detail'
import { IProductResult } from '@/service/index'
const state = reactive({
  show: false,
  sortRules: [] as Record<string, any>[],
  categories: [
    {
      id: '',
      level: 1,
      p_id: '0',
      type_desc: '全部商品',
    },
  ] as ICategory[],
  brands: [] as Record<string, any>[],
  tagsList: [] as string[],
  statusList: [] as string[],
  query: {
    brandName: '',
    categoryId: '',
    sortRule: '',
    upcCode: '',
    status: [],
    tags: [],
    pageNo: 1,
    pageSize: 15,
  } as IProductQueryParams,
  result: {} as IProductQueryResult,
  productList: [] as IProductResult[],
  loadmoreState: 'loading' as any,
})

let status: string[] = []
let tag: string[] = []

const scrollTop = ref<number>(0)

const handleChange = async ({ type, value }) => {
  if (type === 'sidebar') {
    scrollTop.value = -1
    nextTick(() => {
      scrollTop.value = 0
    })
  }
  if (type === 'radio-group') {
    if (state.query.sortRule === '') {
      state.query.sortRule = 'priceasc'
    } else if (state.query.sortRule === 'priceasc') {
      state.query.sortRule = 'pricedesc'
    } else if (state.query.sortRule === 'pricedesc') {
      state.query.sortRule = 'priceasc'
    }
  }
  state.productList = []
  state.loadmoreState = 'loading'
  await getProductList()
}

const handleSearch = async () => {
  state.productList = []
  state.loadmoreState = 'loading'
  await getProductList()
}

const handleScrolltolower = () => {
  if (state.query.pageNo < state.result.pages) {
    handleReload()
  } else if (state.query.pageNo === state.result.pages) {
    state.loadmoreState = 'finished'
  }
}
const handleConfirm = async (type) => {
  if (type === 'popup') {
    state.show = false
  }
  state.productList = []
  state.loadmoreState = 'loading'
  await getProductList()
}

const handleCancel = (type) => {
  if (type === 'popup') {
    state.query.status = []
    state.query.tags = []
    state.show = false
  }
  state.productList = []
  state.loadmoreState = 'loading'
  getProductList()
}

const handleModal = () => {
  state.query.status = status
  state.query.tags = tag
  state.show = false
}

const getProductList = async () => {
  const {
    loading: loadingProductQuery,
    data: productQueryData,
    run: runProductQuery,
  } = useRequest<IProductQueryResult>(() => productQuery(state.query))
  const data = await runProductQuery()
  state.result = data
  state.productList = [...state.productList, ...data.records]
  if (state.query.pageNo >= state.result.pages) {
    state.loadmoreState = 'finished'
  }
}
const handleFilter = () => {
  status = state.query.status
  tag = state.query.tags
  state.show = true
}

onLoad(async () => {
  const {
    loading: loadingQueryConditions,
    data: queryConditionData,
    run: runQueryConditions,
  } = useRequest<IQueryConditionResult>(() => getQueryCondition())
  const data = await runQueryConditions()
  data.sortRules.forEach((item: ISortRule) => {
    if (!item.sortLabel.includes('价格')) {
      state.sortRules.push({
        label: item.sortLabel,
        value: item.sortField,
      })
    }
  })
  data.categories.forEach((item: ICategory) => {
    state.categories.push(item)
  })
  data.brands.forEach((item: IBrand) => {
    state.brands.push({
      label: item.brandName,
      value: item.id,
    })
  })
  state.query.sortRule = data.sortRules[0].sortField
  state.query.categoryId = ''
  state.query.brandName = ''
  state.statusList = data.statusList
  state.tagsList = data.tags

  await getProductList()
})

const handleReload = async () => {
  state.query.pageNo += 1
  state.loadmoreState = 'loading'
  await getProductList()
}
</script>

<style lang="scss" scoped>
.category {
  :deep(.wd-cell-group__title) {
    padding: 0;
  }
  :deep(.wd-sidebar) {
    // width: auto;
  }
  .category-sticky {
    display: flex;
    align-items: center;
    width: calc(100vw - 208rpx);
    height: 120rpx;
    padding: 0 !important;
    margin-bottom: -8rpx;
    background: white;
    .category-filter {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 120rpx;
      box-shadow: -5px 0px 5px -5px rgba(0, 0, 0, 0.3);
    }
  }
}
.wraper {
  display: flex;
  height: calc(
    100vh - var(--window-top) - var(--window-bottom) - constant(safe-area-inset-bottom) - 190rpx
  );
  height: calc(
    100vh - var(--window-top) - var(--window-bottom) - env(safe-area-inset-bottom) - 190rpx
  );
  overflow: hidden;
}
.content {
  flex: 1;
  transition: transform 0.3s ease;
}
.category-scroll-view {
  box-sizing: border-box;
  height: calc(
    100vh - var(--window-top) - var(--window-bottom) - constant(safe-area-inset-bottom) - 182rpx
  );
  height: calc(
    100vh - var(--window-top) - var(--window-bottom) - env(safe-area-inset-bottom) - 182rpx
  );
  background: #fff;
}
</style>
<style lang="scss">
.category-radio-group {
  flex: 1 !important;
  padding: 0 !important;
  .wd-radio.is-button-radio {
    width: auto !important;
    padding: 0 !important;
    padding-left: 15rpx !important;
    .wd-radio__label {
      min-width: 104rpx !important;
      height: 56rpx !important;
      padding: 0 !important;
      font-size: 24rpx !important;
      line-height: 56rpx !important;
    }
  }
}
</style>
